package com.dk.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.data.Result;
import com.dk.em.ConstantEnum;
import com.dk.entity.TAdminDTO;
import com.dk.pojo.TAuction;
import com.dk.pojo.TAuctionOrder;
import com.dk.pojo.TDeposit;
import com.dk.service.ITAuctionOrderService;
import com.dk.service.ITAuctionService;
import com.dk.service.ITDepositService;
import com.dk.util.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-30
 */
@RestController
@RequestMapping("/tAuctionController")
@Api(value = "拍卖管理")
public class TAuctionController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITAuctionService auctionService;

    @Autowired
    private ITDepositService depositService;

    @Autowired
    private ITAuctionOrderService orderService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    //查询全部拍卖商品
    @ApiOperation(value = "查询全部拍卖商品")
    @GetMapping("findAll")
    public Result findAll() {

        //查询缓存中所有需要缓存的商品
        List<TAuction> auctionGoods = (List<TAuction>) redisTemplate.boundHashOps("auctionGoods").values();
        if (auctionGoods == null || auctionGoods.size() == 0) {
            //查询拍卖商品
            QueryWrapper Wrapper = new QueryWrapper<TAuction>();
            //审核通过
            Wrapper.eq("status", 1);
            //拍卖时间在开始时间与结束时间之间
            Date date = new Date();
            //当前时间大于开始时间(开始时间小于等于当前时间)
            Wrapper.le("start_time", date);   //le: 小于
            //当前时间小于结束时间(结束时间大于或等于当前时间)
            Wrapper.ge("end_time", date);     //ge: 大于
            auctionGoods = auctionService.list(Wrapper);

            //放到redis中
            for (TAuction auction : auctionGoods) {
                redisTemplate.boundHashOps("auctionGoods").put(auction.getId(),auction);
                //将初始价格单独放到redis中
                redisTemplate.boundValueOps(auction.getGoodsId() + "price").set("10000");
            }
        }

        return Result.bulid(ConstantEnum.SUCCESS).setResult(auctionGoods);
    }

    //点击进入拍卖商品按钮
    @ApiOperation(value = "拍卖商品详情页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path")
    })
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    private Result findById(@PathVariable("id") Long id){
        TAuction auction = auctionService.getById(id);
        return Result.bulid(ConstantEnum.SUCCESS).setResult(auction);
    }

    //交付定金
    @ApiOperation(value = "交付定金")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "token",value = "token值",required = true,paramType = "path")
    })
    @RequestMapping(value = "/toPay/{id}/{token}",method = RequestMethod.GET)
    private String toPay(@PathVariable("id") Long id,@PathVariable("token") String token){

        //序列化  只支持 string  hash 类型
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        TAuction auction = auctionService.getById(id);
        IdWorker idWorker = new IdWorker();
        long l = idWorker.nextId();
        String WIDout_trade_no = Long.toString(l);
        String WIDtotal_amount = "2000";
        String WIDsubject = auction.getTitle();
        String WIDbody = "定金交付";

        //添加定金信息
        TDeposit tDeposit = new TDeposit();
        tDeposit.setTradeNo(WIDout_trade_no);
        tDeposit.setAdminId(tAdminDTO.getId());
        tDeposit.setAuctionId(id.intValue());
        depositService.save(tDeposit);

        //去支付
        TradeController tradeController = new TradeController();
        String result = tradeController.toAliPay(WIDout_trade_no, WIDtotal_amount, WIDsubject, WIDbody);
        return result;
    }

    //点击加价
    @ApiOperation(value = "加价")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path"),
            @ApiImplicitParam(name = "token",value = "token值",required = true,paramType = "path")
    })
    @RequestMapping(value = "/addPrice/{id}/{token}",method = RequestMethod.GET)
    private Result addPrice(@PathVariable("id") Long id,@PathVariable("adminId") String token){
        //获取用户
        String str = (String) redisTemplate.boundValueOps(token).get();
        TAdminDTO tAdminDTO = JSONObject.parseObject(str, TAdminDTO.class);

        TAuction auction = auctionService.getById(id);
        Long increment = redisTemplate.boundValueOps(auction.getGoodsId() + "price").increment(1000L);
        //查询该用户的竞价记录
        QueryWrapper Wrapper = new QueryWrapper<TDeposit>();
        //用户id
        Wrapper.eq("admin_id",tAdminDTO.getId());
        //拍卖商品id
        Wrapper.le("auction_id", id);
        TDeposit deposit = depositService.getOne(Wrapper);

        //修改用户竞价
        deposit.setPrice(increment);
        depositService.updateById(deposit);

        return Result.bulid(ConstantEnum.SUCCESS).setResult(deposit);
    }

    //确定价格最高者获得商品
    public Result getAdmin(Long id){
        TAuction auction = auctionService.getById(id);
        Long price = redisTemplate.boundValueOps(auction.getGoodsId() + "price").increment(0L);
        //无人竞价
        if (price == 10000L){
            auction.setStatus(2);
            auctionService.updateById(auction);
            return Result.bulid(ConstantEnum.ERROR).setResult("该商品无人竞价");
        }
        //查询该用户的竞价记录
        QueryWrapper Wrapper = new QueryWrapper<TDeposit>();
        //拍卖商品id
        Wrapper.eq("auction_id",id);
        //价格最高者
        Wrapper.eq("price",price);
        TDeposit deposit = depositService.getOne(Wrapper);

        IdWorker worker = new IdWorker();
        long nextId = worker.nextId();
        //增加拍卖订单
        TAuctionOrder order = new TAuctionOrder();
        order.setAuctionId(auction.getId());
        order.setMoney(new BigDecimal(price));
        order.setAdminId(deposit.getAdminId());
        order.setSellerId(auction.getSellerId());
        order.setOutTradeNo(nextId + "");
        order.setStatus(1);
        //拍卖人地址 电话  姓名
//        order.setAuctionAddress();
//        order.setAuctionMobile();
//        order.setAuction();
        orderService.save(order);
        //退定金
        QueryWrapper Wrapper2 = new QueryWrapper<TDeposit>();
        //拍卖商品id
        Wrapper.eq("auction_id",id);
        List<TDeposit> deposits = depositService.list(Wrapper2);
        IdWorker idWorker = new IdWorker();
        TradeController tradeController = new TradeController();
        for (TDeposit tDeposit : deposits) {
            //订单号   流水号  退款金额  退款原因  退款请求号
            String WIDTRout_trade_no = tDeposit.getTradeNo();
            String WIDTRtrade_no = tDeposit.getTransactionNo();
            String WIDTRrefund_amount = "2000";
            String WIDTRrefund_reason = "定金退还";
            String WIDTRout_request_no = tDeposit.getTradeNo();
            tradeController.alipayTradeRefund(WIDTRout_trade_no,WIDTRtrade_no,WIDTRrefund_amount,WIDTRrefund_reason,WIDTRout_request_no);
        }
        return Result.bulid(ConstantEnum.SUCCESS).setResult("该商品已被拍下");
    }

    //支付拍卖商品
    @ApiOperation(value = "支付拍卖商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true,paramType = "path")
    })
    @RequestMapping(value = "/toPayOrder/{id}",method = RequestMethod.GET)
    private String toPayOrder(@PathVariable("id") Long id){

        //查询订单表
        QueryWrapper Wrapper = new QueryWrapper<TAuctionOrder>();
        //拍卖商品id
        Wrapper.eq("auction_id",id);
        TAuctionOrder order = orderService.getOne(Wrapper);

        Message<TAuctionOrder> message = MessageBuilder.withPayload(order).build();
        //发送mq异步延时消息
        rocketMQTemplate.syncSend("auctionOrder",message,3000,16);

        TAuction auction = auctionService.getById(id);

        String WIDout_trade_no = order.getAuctionId().toString();
        String WIDtotal_amount = order.getMoney().toString();
        String WIDsubject = auction.getTitle();
        String WIDbody = "拍卖商品支付";
        TradeController tradeController = new TradeController();
        String result = tradeController.toAliPay(WIDout_trade_no, WIDtotal_amount, WIDsubject, WIDbody);
        return result;
    }
}
